<template>
  <div>
    <div class="video-title">
      <span class="tip" :class="[progressData.videoFinish?'success':'error']"></span>
      <span>{{videoData.videoName}}</span>
    </div>
    <video-player
      ref="videoPlayer"
      class="video-player vjs-custom-skin"
      :playsinline="true"
      :options="playerOptions"
      @play="onPlayerPlay($event)"
      @ready="onPlayerReady($event)"
      @pause="onPlayerPause($event)"
      @ended="onPlayerEnded($event)"
      @timeupdate="onPlayerTimeUpdate"
    />
    <el-dialog
      :visible.sync="qsVisible"
      width="50%"
      title="及时问答"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <qu-show :curIdx="1" :answer="answer" :currentQu="currentQu" @change="answerQu" />
    </el-dialog>
  </div>
</template>

<script>
import { videoPlayer } from "vue-video-player";
import "video.js/dist/video-js.css";
import "vue-video-player/src/custom-theme.css";
import "videojs-contrib-hls";
import { updateProgress } from "@/api/course";
import QuShow from "./comp/quShow.vue";
import { getQuOne } from "@/api/question";
// import {videojs} from "vue-video-player/dist/ssr";
export default {
  name: "VideoPlayer",
  components: { videoPlayer, QuShow },
  props: {
    videoData: {
      type: Object
    },
    type: {
      type: String,
      default: "application/x-mpegURL"
    }
  },
  data() {
    return {
      answer: [
        {
          order: 1,
          completed: false,
          uanswer: "",
          uanswers: []
        }
      ],
      currentQu: {},
      notFinishRate: [1.0],
      isFinishRate: [0.7, 1.0, 1.5, 2.0],
      time: null,
      qsVisible: false,
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",
        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: this.type, // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: this.videoData.videoUrl // url地址
          }
        ],
        hls: true,
        poster: "", // 你的封面地址
        width: 960, // 播放器宽度
        height: 720,
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      },
      progressData: {
        chapterId: String(this.$route.query.chapterId),
        courseId: String(this.$route.query.courseId),
        videoFinish: this.videoData.isFinish,
        videoId: String(this.videoData.videoId),
        videoNowDuration: this.videoData.viewPoint
      }
    };
  },
  watch: {
    videoData: {
      handler(newV) {
        console.log("videoInfo", newV);
        this.videoData = newV;
        this.playerOptions.sources[0].src = newV.videoUrl;
        this.progressData.videoId = String(newV.videoId);
        this.progressData.videoFinish = newV.isFinish;
        this.progressData.chapterId = this.$route.query.chapterId;
        this.playerOptions.playbackRates =
          newV.isFinish == 1 ? this.isFinishRate : this.notFinishRate;
      },
      immediate: true
    }
  },
  created() {
    this.playerOptions.sources[0].src = this.videoData.videoUrl;
  },
  methods: {
    onPlayerReady() {
      let time = this.videoData.viewPoint;
      if (time && this.videoData.isFinish != 1) {
        this.$refs.videoPlayer.player.currentTime(time);
      }
      if (this.videoData.isFinish != 1) {
        this.$refs.videoPlayer.$el.firstChild
          .getElementsByClassName("vjs-control-bar")[0]
          .getElementsByClassName(
            "vjs-progress-control"
          )[0].style.pointerEvents = "none";
      }
    },
    onPlayerPlay(e) {
      this.$emit("play", e);
    },
    onPlayerPause(e) {
      const currentDuration = ~~this.$refs.videoPlayer.player.currentTime();
      console.log(currentDuration);
      this.progressData.videoNowDuration = currentDuration;
      if (this.videoData.isFinish != 1) {
        this.updateProgress();
      }
      this.$emit("pause", e);
    },
    onPlayerEnded(e) {
      if (this.videoData.isFinish != 1) {
        this.progressData.videoFinish = 1;
        this.updateProgress();
      }
      this.$emit("ended", e);
    },
    onPlayerTimeUpdate() {
      const currentDuration = ~~this.$refs.videoPlayer.player.currentTime();
      if (this.time !== currentDuration) {
        this.time = currentDuration;
        // 上传进度
        if (this.time % 10 == 0 && this.time > 0) {
          this.progressData.videoNowDuration = currentDuration;
          if (this.videoData.isFinish != 1) {
            this.updateProgress();
          }
        }

        // 弹出答题
        if (this.videoData.isFinish != 1) {
          const qsTime = this.videoData.problemPoint.filter(item => {
            if (item.point == currentDuration) {
              return item;
            }
          });
          if (qsTime.length > 0) {
            getQuOne(qsTime[0].objId).then(res => {
              if (res.code == 200) {
                this.currentQu = res.data;
                this.qsVisible = true;
                this.$refs.videoPlayer.player.pause();
              }
            });
          }
        }
      }
    },
    // 上传观看进度
    updateProgress() {
      updateProgress(this.progressData);
    },
    answerQu() {
      this.qsVisible = false;
      this.$refs.videoPlayer.player.play();
    }
  }
};
</script>

<style  scoped>
.video-title {
  display: flex;
  flex-direction: row;
  /*justify-content: center;*/
  text-align: center;
  margin-bottom: 10px;
  align-items: center;
  font-size: 20px;
}
.tip {
  display: inline-block;
  height: 15px;
  width: 15px;
  border-radius: 50%;
  margin-right: 10px;
}
</style>
